package com.yueqian.framework.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.yueqian.framework.constants.CommonConstants;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Objects;


@Component("metaObjectHandler")
public class CustomMetaObjectHandler implements MetaObjectHandler {
	@Override
	public void insertFill(MetaObject metaObject) {
		Long userId = getUserIdFromContext();
		this.setFieldValByName("creatorId", userId, metaObject);
		this.setFieldValByName("updaterId", userId, metaObject);
		LocalDateTime now = LocalDateTime.now();
		this.setFieldValByName("creatorTime", now, metaObject);
		this.setFieldValByName("updateTime", now, metaObject);
	}

	@Override
	public void updateFill(MetaObject metaObject) {
		Long userId = getUserIdFromContext();
		this.setFieldValByName("updaterId", userId, metaObject);
		this.setFieldValByName("updateTime",  LocalDateTime.now(), metaObject);
	}


	private Long getUserIdFromContext() {
		HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
		Long userId = (Long) request.getAttribute(CommonConstants.REQUEST_ATTRIBUTE_USER_ID);
		if (userId != null) {
			return userId;
		} else {
			return 0L;
		}
	}
}
